import VueRouter from "vue-router";

//导入组件
import Login from '../views/Login' 
import Home from '../views/Home'
import Fanju from '../views/cartoon/Fanju'
import FanjuItem from '../views/cartoon/FanjuItem'
import Main from '../views/Main'
import aa from '../views/aa'
const router=new VueRouter({
    mode:'hash',
    routes:[
        {
            path:'/',component:Main,redirect:'/home',
            children:[
                {path:'home',name:'home',meta:{isAuth:true},component:Home},
                {path:'fanju',name:'fanju',meta:{isAuth:true},component:Fanju},
                {path:'fanjuItem',name:'fanjuItem',meta:{isAuth:true},component:FanjuItem}
            ] 
        },
        {path:'/login',name:'login',component:Login},
        {path:'/aa',name:'aa',component:aa}
    ]
})

//全局前置路由写在这里
router.beforeEach((to, from, next) => {
    // 判断token是否存在
    const token = localStorage.getItem('userToken')
    // token不存在，说明当前用户是未登录，应该跳转至登录页
    if ((!token || token==null)&& to.meta.isAuth === true) {
      next({ name: 'login' })
    } else if (token && to.name === 'login') {//有token了，不能进入登录页。返回原来的页
      next({ name: from.name })
    } else {//其他情况。有token，跳转的不是登录页，放行
      next()
    }
  })

const originPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originPush.call(this, location).catch(err => err)
}

export default router